﻿using System.Security.Cryptography;

partial class Program
{
    //AES（高级加密标准）是一种对称加密算法，安全性较高，适用于大多数场景。
    //key 必须是 16、24 或 32 字节长度。    使用相同的 key 才能正确解密。
    public static string Encrypt(string plainText, string key)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        using Aes aes = Aes.Create();
        aes.Key = keyBytes;
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.PKCS7;

        using MemoryStream ms = new();
        using CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
        cs.Write(plainBytes, 0, plainBytes.Length);
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }

    public static string Decrypt(string cipherText, string key)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        using Aes aes = Aes.Create();
        aes.Key = keyBytes;
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.PKCS7;

        using MemoryStream ms = new();
        using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        cs.Write(cipherBytes, 0, cipherBytes.Length);
        cs.FlushFinalBlock();
        return Encoding.UTF8.GetString(ms.ToArray());
    }
    //MD5 是一种不可逆的哈希算法，常用于密码存储或数据完整性校验。
    public static string ToMD5(string input)
    {
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        byte[] hashBytes = MD5.HashData(inputBytes);

        StringBuilder sb = new();
        foreach (byte b in hashBytes)
        {
            sb.Append(b.ToString("x2"));
        }
        return sb.ToString();
    }

    //RSA 是一种非对称加密算法，适合需要公钥和私钥的场景。
    //公钥用于加密，私钥用于解密。    密钥生成需使用 RSACryptoServiceProvider。
    public static string RSAEncrypt(string plainText, RSAParameters publicKey)
    {
        using RSACryptoServiceProvider rsa = new();
        rsa.ImportParameters(publicKey);
        byte[] encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(plainText), false);
        return Convert.ToBase64String(encryptedData);
    }

    public static string RSADecrypt(string cipherText, RSAParameters privateKey)
    {
        using RSACryptoServiceProvider rsa = new();
        rsa.ImportParameters(privateKey);
        byte[] decryptedData = rsa.Decrypt(Convert.FromBase64String(cipherText), false);
        return Encoding.UTF8.GetString(decryptedData);
    }
}
